﻿#ifndef BYTES_H
#define BYTES_H

#include <QByteArray>

// 取 uint16_t 的高字节
inline uint8_t getHByte(uint16_t n) noexcept
{
    return static_cast<uint8_t>(n >> 8);
}

// 取 uint16_t 的低字节
inline uint8_t getLByte(uint16_t n) noexcept
{
    return static_cast<uint8_t>(n & 0xFF);
}

// 按大端序将 uint32_t 转换成 QByteArray
inline QByteArray ui32ToBytesBE(uint32_t n) noexcept
{
    QByteArray arr;
    arr.append(static_cast<char>((n >> 24) & 0xFF));
    arr.append(static_cast<char>((n >> 16) & 0xFF));
    arr.append(static_cast<char>((n >> 8) & 0xFF));
    arr.append(static_cast<char>(n & 0xFF));
    return arr;
}

// 按小端序将 uint32_t 转换成 QByteArray
inline QByteArray ui32ToBytesLE(uint32_t n) noexcept
{
    QByteArray arr;
    arr.append(static_cast<char>(n & 0xFF));
    arr.append(static_cast<char>((n >> 8) & 0xFF));
    arr.append(static_cast<char>((n >> 16) & 0xFF));
    arr.append(static_cast<char>((n >> 24) & 0xFF));
    return arr;
}

// QByteArray 取某两个连续字节转成 uint16_t，大端序
inline uint16_t getUi16FromBytesBE(const QByteArray& bytes, uint16_t idx) noexcept
{
    if (idx + 1 >= bytes.size()) return 0;
    return (static_cast<uint16_t>(static_cast<uint8_t>(bytes[idx])) << 8) |
           (static_cast<uint16_t>(static_cast<uint8_t>(bytes[idx + 1])));
}

// QByteArray 取某两个连续字节转成 uint16_t，小端序
inline uint16_t getUi16FromBytesLE(const QByteArray& bytes, uint16_t idx) noexcept
{
    if (idx + 1 >= bytes.size()) return 0;
    return (static_cast<uint16_t>(static_cast<uint8_t>(bytes[idx + 1])) << 8) |
           (static_cast<uint16_t>(static_cast<uint8_t>(bytes[idx])));
}

// QByteArray 取某个字节转成 uint8_t
inline uint8_t getByteFromBytes(const QByteArray& bytes, uint16_t idx) noexcept
{
    if (idx >= bytes.size()) return 0;
    return static_cast<uint8_t>(bytes[idx]);
}

#endif // BYTES_H
